<?php
declare (strict_types = 1);

namespace app\model;

use app\common\service\redis\PoolRedis;
use think\Model;
use think\model\relation\BelongsTo;
use think\model\relation\HasMany;

/**
 * @mixin \think\Model
 */
class AdminAttendanceRecord extends Model
{

    const ATTENDANCE_COUNT_CACHE_KEY = 'attendance_record:';

    const TYPE_ARR = [0=>'人脸'];
    const STATUS_ARR = [0=> '失败', 1=> '正常', 2=> '迟到', 3=> '早退'];

    const ERROR = 0; // 失败
    const SUCCESS = 1; // 正常
    const CD = 2; // 迟到
    const ZT = 3; // 早退

    //
    protected $name = 'admin_attendance_record';

    public function attendance(): BelongsTo {
        return $this->belongsTo('AdminAttendanceSys', 'attendance_id', 'id')
            ->bind(['title','grade']);
    }

    public function staff(): BelongsTo {
        return $this->belongsTo(AdminStaff::class, 'staff_id');
    }

    public function icCard(): hasMany {
        return $this->hasMany('AdminStaffIcCard', 'staff_id', 'staff_id')
            ->where('is_delete', 0)
            ->hidden(['is_delete','update_time']);
    }

    public function getClockInTypeTextAttr($value, $data)
    {
        return self::TYPE_ARR[$data['clock_in_type']];
    }

    public function getStatusTextAttr($value, $data)
    {
        return self::STATUS_ARR[$data['status']];
    }

    public static function onAfterWrite($model)
    {
        // 写入缓存
        $redis = PoolRedis::instance();
        $cacheKey = self::ATTENDANCE_COUNT_CACHE_KEY."{$model->getAttr('attendance_id')}:".date('Y-m-d');
        $redis->sAdd($cacheKey, $model->getAttr('staff_id'));
        $redis->expire($cacheKey, 3*24*60*60); // 3天后过期
    }
}
